package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.community.CommunityCategory;
import com.zbkj.common.model.product.ProductCategory;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.CommunityCategorySaveRequest;
import com.zbkj.common.request.CommunityCategorySearchRequest;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.result.CommunityResultCode;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.service.dao.community.CommunityCategoryDao;
import com.zbkj.service.service.CommunityCategoryService;
import com.zbkj.service.service.CommunityNotesService;
import com.zbkj.service.service.SystemAdminService;
import com.zbkj.service.util.BrandUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * CommunityCategory 接口实现
 +----------------------------------------------------------------------
 */
@Service
@Slf4j
public class CommunityCategoryServiceImpl extends ServiceImpl<CommunityCategoryDao, CommunityCategory> implements CommunityCategoryService {

    @Resource
    private CommunityCategoryDao dao;

    @Autowired
    private CommunityNotesService notesService;
    @Autowired
    private SystemAdminService adminService;

    /**
     * 社区分类分页列表
     *
     * @param request 请求参数
     * @return 分页列表
     */
    @Override
    public PageInfo<CommunityCategory> findPageList(CommunityCategorySearchRequest request) {
        Page<CommunityCategory> page = PageHelper.startPage(request.getPage(), request.getLimit());
        LambdaQueryWrapper<CommunityCategory> lqw = Wrappers.lambdaQuery();
        lqw.select(CommunityCategory::getId, CommunityCategory::getName, CommunityCategory::getSort,
                CommunityCategory::getIsShow, CommunityCategory::getCreateTime);
        if (StrUtil.isNotBlank(request.getName())) {
            lqw.like(CommunityCategory::getName, URLUtil.decode(request.getName()));
        }
        if (ObjectUtil.isNotNull(request.getIsShow())) {
            lqw.eq(CommunityCategory::getIsShow, request.getIsShow());
        }
        lqw.eq(CommunityCategory::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        lqw.orderByDesc(CommunityCategory::getSort, CommunityCategory::getId);
        List<CommunityCategory> list = dao.selectList(lqw);
        return CommonPage.copyPageInfo(page, list);
    }

    @Override
    public PageInfo<CommunityCategory> findPageListBrand(CommunityCategorySearchRequest request) {
        Page<CommunityCategory> page = PageHelper.startPage(request.getPage(), request.getLimit());
        LambdaQueryWrapper<CommunityCategory> lqw = Wrappers.lambdaQuery();
        lqw.select(CommunityCategory::getId, CommunityCategory::getName, CommunityCategory::getSort,
                CommunityCategory::getIsShow, CommunityCategory::getCreateTime,CommunityCategory::getBrandShow,CommunityCategory::getBrandId);

        if (StrUtil.isNotBlank(request.getName())) {
            lqw.like(CommunityCategory::getName, URLUtil.decode(request.getName()));
        }
//        lqw.eq(CommunityCategory::getBrandId,37);
        if (ObjectUtil.isNotNull(request.getIsShow())) {
            lqw.eq(CommunityCategory::getIsShow, request.getIsShow());
        }
        lqw.eq(CommunityCategory::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        lqw.eq(CommunityCategory::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.orderByDesc(CommunityCategory::getSort, CommunityCategory::getId);
        List<CommunityCategory> productCategories = dao.selectList(lqw);
        // 批量更新需要更新的品牌
        List<CommunityCategory> brandsToUpdate = new ArrayList<>();
        for (CommunityCategory productCategory : productCategories) {
            String brandShow = productCategory.getBrandShow();
            JSONObject object;
            if (ObjectUtil.isNull(brandShow)) {
                object = new JSONObject();
            } else {
                object = new JSONObject(brandShow);
            }
            String targetBrandId = BrandUtil.getBrandId().toString();
            if (!object.containsKey(targetBrandId)) {
                JSONArray jsonArray = new JSONArray();
                JSONObject innerObject = new JSONObject();
                innerObject.put("paixu", 0);
                innerObject.put("bc_time", DateUtil.formatDate(new Date()));
                innerObject.put("bu_date", DateUtil.formatDate(new Date()));
                innerObject.put("bis_show", 0);
                jsonArray.put(innerObject);
                object.put(targetBrandId, jsonArray);
            }
            productCategory.setBrandShow(object.toString());
            brandsToUpdate.add(productCategory);
        }
        // 批量更新数据库
        if (!brandsToUpdate.isEmpty()) {
            brandsToUpdate.forEach(dao::updateById);
        }
        LambdaQueryWrapper<CommunityCategory> lqw2 = Wrappers.lambdaQuery();
        lqw2.select(CommunityCategory::getId, CommunityCategory::getName, CommunityCategory::getSort,
                CommunityCategory::getIsShow, CommunityCategory::getCreateTime,CommunityCategory::getBrandShow,CommunityCategory::getBrandId);
        if (StrUtil.isNotBlank(request.getName())) {
            lqw2.like(CommunityCategory::getName, URLUtil.decode(request.getName()));
        }
//        lqw.eq(CommunityCategory::getBrandId,37);
        if (ObjectUtil.isNotNull(request.getIsShow())) {
            lqw2.eq(CommunityCategory::getIsShow, request.getIsShow());
        }
        if (ObjectUtil.isNotNull(request.getBrandName())){
            LambdaQueryWrapper<SystemAdmin> lqwadmin = Wrappers.lambdaQuery();
            lqwadmin.eq(SystemAdmin::getRealName, URLUtil.decode(request.getBrandName()));
            SystemAdmin one = adminService.getOne(lqwadmin);
            if (ObjectUtil.isNotNull(one)){
                lqw2.eq(CommunityCategory::getBrandId,one.getId());
            }
        }
        if (ObjectUtil.isNotNull(request.getAuditStatus())){
            if (request.getAuditStatus()==0){
                //log.info("品牌商id："+BrandUtil.getBrandId());
                lqw2.eq(CommunityCategory::getBrandId,BrandUtil.getBrandId());
            }else{
                lqw2.notIn(CommunityCategory::getBrandId,BrandUtil.getBrandId());
            }
        }
        lqw2.eq(CommunityCategory::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        lqw2.eq(CommunityCategory::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw2.orderByDesc(CommunityCategory::getSort, CommunityCategory::getId);
        List<CommunityCategory> list = dao.selectList(lqw2);
        List<CommunityCategory> productCategorys = new ArrayList<>();
        for (CommunityCategory productCategory : list) {
            String brandShow = productCategory.getBrandShow();
            Integer brandId = productCategory.getBrandId();
            if (brandId!=null){
                SystemAdmin byId = adminService.getById(brandId);
                if (byId != null) {
                    productCategory.setBrandName(byId.getRealName());
                }
            }else{
                productCategory.setBrandName("其他");
            }
            log.info("item:{}", brandShow);
            if (brandShow != null) {
                JSONObject jsonObject = new JSONObject(brandShow);
                JSONArray array = jsonObject.getJSONArray(BrandUtil.getBrandId().toString());
                if (array != null && !array.isEmpty()) {
                    JSONObject item = array.getJSONObject(0);
                    Integer bisShow = item.getInt("bis_show");
                    productCategory.setBrandIsShow(bisShow);
                }
            }else {
                productCategory.setBrandIsShow(0);
            }
            productCategorys.add(productCategory);
        }
      /*  LambdaQueryWrapper<CommunityCategory> lqw = Wrappers.lambdaQuery();
        lqw.select(CommunityCategory::getId, CommunityCategory::getName, CommunityCategory::getSort,
                CommunityCategory::getIsShow, CommunityCategory::getCreateTime,CommunityCategory::getBrandShow);
        if (StrUtil.isNotBlank(request.getName())) {
            lqw.like(CommunityCategory::getName, URLUtil.decode(request.getName()));
        }
//        lqw.eq(CommunityCategory::getBrandId,37);
        if (ObjectUtil.isNotNull(request.getIsShow())) {
            lqw.eq(CommunityCategory::getIsShow, request.getIsShow());
        }
        lqw.eq(CommunityCategory::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        lqw.orderByDesc(CommunityCategory::getSort, CommunityCategory::getId);
        List<CommunityCategory> list = dao.selectList(lqw);
        List<CommunityCategory> productCategorys = new ArrayList<>();
        for (CommunityCategory productCategory : list) {
            String brandShow = productCategory.getBrandShow();
            log.info("item:{}", brandShow);
            if (brandShow != null) {
                JSONObject jsonObject = new JSONObject(brandShow);
                JSONArray array = jsonObject.getJSONArray(BrandUtil.getBrandId().toString());
                if (array != null && !array.isEmpty()) {
                    JSONObject item = array.getJSONObject(0);
                    Integer bisShow = item.getInt("bis_show");
                    productCategory.setBrandIsShow(bisShow);
                }
            } else {
                productCategory.setBrandIsShow(0);
            }
            productCategorys.add(productCategory);
        }*/
        return CommonPage.copyPageInfo(page, list);
    }


    /**
     * 保存社区分类
     *
     * @param request 请求参数
     */
    @Override
    public void add(CommunityCategorySaveRequest request) {
        if (isExistName(request.getName(), 0)) {
            throw new AppException(CommunityResultCode.COMMUNITY_CATEGORY_EXIST);
        }
        CommunityCategory category = new CommunityCategory();
        BeanUtils.copyProperties(request, category, "id");
        boolean save = save(category);
        if (!save) {
            throw new AppException("添加社区分类失败");
        }
    }

    @Override
    public void addBrand(CommunityCategorySaveRequest request) {
        if (isExistNameBrand(request.getName(), 0)) {
            throw new AppException(CommunityResultCode.COMMUNITY_CATEGORY_EXIST);
        }
        CommunityCategory category = new CommunityCategory();
        BeanUtils.copyProperties(request, category, "id");
        category.setBrandId(BrandUtil.getBrandIdByUrl());
        // 新增时显示
        if (category.getIsShow().equals(1)) {
            JSONObject jsonObject = new JSONObject();
            JSONArray array = new JSONArray();
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("paixu", 0);
            jsonObject1.put("bc_time", DateUtil.formatDate(new Date()));
            jsonObject1.put("bu_date", DateUtil.formatDate(new Date()));
            jsonObject1.put("bis_show", 1);
            array.add(jsonObject1);
            jsonObject.put("" + BrandUtil.getBrandId(), array);
            category.setBrandShow(jsonObject.toString());
        }

        boolean save = save(category);
        if (!save) {
            throw new AppException("添加社区分类失败");
        }
    }

    /**
     * 编辑社区分类
     *
     * @param request 请求参数
     */
    @Override
    public void edit(CommunityCategorySaveRequest request) {
        if (ObjectUtil.isNull(request.getId())) {
            throw new AppException(CommunityResultCode.COMMUNITY_CATEGORY_ID_NULL);
        }
        CommunityCategory category = getByIdExpetion(request.getId());

        if (!category.getName().equals(request.getName()) && isExistName(request.getName(), request.getId())) {
            throw new AppException(CommunityResultCode.COMMUNITY_CATEGORY_EXIST);
        }
        BeanUtils.copyProperties(request, category);

        String brandShow = category.getBrandShow();
        JSONObject jsonObject = new JSONObject(brandShow);
        // 获取 "37" 对应的数组
        JSONArray array = jsonObject.getJSONArray(BrandUtil.getBrandId().toString());
        // 获取数组中的第一个元素
        JSONObject item = array.getJSONObject(0);
        // 获取 bis_show 字段的值
        if (category.getIsShow() == 1) {
            item.put("bis_show", 1);
        } else {
            item.put("bis_show", 0);
        }
        category.setBrandShow(jsonObject.toString());

        boolean update = updateById(category);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("编辑社区分类失败"));
        }
    }

    /**
     * 删除社区分类
     * @param id 分类ID
     */
    @Override
    public void deleteById(Integer id) {
        CommunityCategory category = getByIdExpetion(id);

        if (notesService.isUseCategory(id)) {
            throw new AppException(CommunityResultCode.COMMUNITY_CATEGORY_USING);
        }
        category.setIsDel(Constants.COMMON_IS_FILED_ONE);
        boolean update = updateById(category);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("删除社区分类失败"));
        }
    }

    /**
     * 获取分类Map
     * @param cateIdList 分类ID列表
     * @return Map<id，name>
     */
    @Override
    public Map<Integer, String> getMapInIdList(List<Integer> cateIdList) {
        LambdaQueryWrapper<CommunityCategory> lqw = Wrappers.lambdaQuery();
        lqw.select(CommunityCategory::getId, CommunityCategory::getName);
        lqw.in(CommunityCategory::getId, cateIdList);
        lqw.eq(CommunityCategory::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        List<CommunityCategory> list = dao.selectList(lqw);
        Map<Integer, String> map = CollUtil.newHashMap();
        list.forEach(e -> {
            map.put(e.getId(), e.getName());
        });
        return map;
    }

    /**
     * 社区分类显示开关
     * @param id 分类ID
     */
    @Override
    public void showSwitch(Integer id) {
        CommunityCategory category = getByIdExpetion(id);
        String brandShow = category.getBrandShow();
        JSONObject jsonObject = new JSONObject(brandShow);
        // 获取 "37" 对应的数组
        JSONArray array = jsonObject.getJSONArray(BrandUtil.getBrandId().toString());
        // 获取数组中的第一个元素
        JSONObject item = array.getJSONObject(0);
        // 获取 bis_show 字段的值
        int bisShow = item.getInt("bis_show");
        if (bisShow != 1) {
            item.put("bis_show", 1);
            category.setIsShow(Constants.COMMON_IS_FILED_ONE);
        } else {
            item.put("bis_show", 0);
            category.setIsShow(Constants.COMMON_IS_FILED_ZERO);
        }
        category.setBrandShow(jsonObject.toString());
        boolean update = updateById(category);
        if (!update) {
            throw new AppException("编辑社区分类显示状态失败");
        }
    }

    /**
     * 根据显示状态获取全部分类列表
     */
    @Override
    public List<CommunityCategory> findListByShow(Integer isShow) {
        LambdaQueryWrapper<CommunityCategory> lqw = Wrappers.lambdaQuery();
        lqw.select(CommunityCategory::getId, CommunityCategory::getName,CommunityCategory::getBrandShow);
        if (ObjectUtil.isNotNull(isShow)) {
            lqw.eq(CommunityCategory::getIsShow, isShow);
        }
        lqw.eq(CommunityCategory::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.eq(CommunityCategory::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        lqw.orderByDesc(CommunityCategory::getSort, CommunityCategory::getId);
        List<CommunityCategory> communityCategories = dao.selectList(lqw);
        List<CommunityCategory> productCategorys = new ArrayList<>();
        Integer brandId = BrandUtil.getBrandIdByUrl();
        for (CommunityCategory productCategory : communityCategories) {
            String brandShow = productCategory.getBrandShow();
            //log.info("item:{}", brandShow);
            if (brandShow != null) {
                JSONObject jsonObject = new JSONObject(brandShow);
                JSONArray array = jsonObject.getJSONArray(String.valueOf(brandId));
                if (array != null && !array.isEmpty()) {
                    JSONObject item = array.getJSONObject(0);
                    Integer bisShow = item.getInt("bis_show");
                    productCategory.setBrandIsShow(bisShow);
                }
            }else {
                productCategory.setBrandIsShow(0);
            }
            productCategorys.add(productCategory);
        }
        return productCategorys;
    }

    private boolean isExistName(String name, Integer id) {
        LambdaQueryWrapper<CommunityCategory> lqw = Wrappers.lambdaQuery();
        lqw.select(CommunityCategory::getId);
        lqw.eq(CommunityCategory::getName, name);
        lqw.eq(CommunityCategory::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.eq(CommunityCategory::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        if (ObjectUtil.isNotNull(id) && id > 0) {
            lqw.ne(CommunityCategory::getId, id);
        }
        lqw.last("limit 1");
        CommunityCategory communityCategory = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(communityCategory);
    }

    private boolean isExistNameBrand(String name, Integer id) {
        LambdaQueryWrapper<CommunityCategory> lqw = Wrappers.lambdaQuery();
        lqw.select(CommunityCategory::getId);
        lqw.eq(CommunityCategory::getName, name);
        lqw.eq(CommunityCategory::getBrandId,BrandUtil.getBrandIdByUrl());
        lqw.eq(CommunityCategory::getIsDel, Constants.COMMON_IS_FILED_ZERO);
        if (ObjectUtil.isNotNull(id) && id > 0) {
            lqw.ne(CommunityCategory::getId, id);
        }
        lqw.last("limit 1");
        CommunityCategory communityCategory = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(communityCategory);
    }

    private CommunityCategory getByIdExpetion(Integer id) {
        CommunityCategory category = getById(id);
        if (ObjectUtil.isNull(category) || category.getIsDel().equals(Constants.COMMON_IS_FILED_ONE)) {
            throw new AppException(CommunityResultCode.COMMUNITY_CATEGORY_NOT_EXIST);
        }
        return category;
    }
}

